import { View, Input } from '@tarojs/components'
import { memo, useState } from 'react'
import { AddOutlined, Exchange, Search as IconSearch } from "@taroify/icons"
import Taro from '@tarojs/taro'
import BtPopup from '@/BtComponents/BtPopup'
import useActivityQrcodeStore, { setFilter, setStatus } from '../../useActivityQrcodeStore'
import { QrcodeStatusEnum } from '../../interface'
import './index.scss'

function Search() {
  const status = useActivityQrcodeStore(state => state.status)
  const [searchKey, setSearchKey] = useState('')
  const [open, setOpen] = useState(false)

  const popupCreateMsg = {
    title: '你要创建哪种活码?',
    list: [
      { text: '创建活码', tip: '客户扫码添加员工时，自动给客户打标签、发欢迎语', onClick: () => Taro.navigateTo({ url: '/pages/createStaffQrcode/index' }) },
      { text: '客户群活码', tip: '客户扫码加入群聊，群人数达到上限后切换新群聊', onClick: () => Taro.navigateTo({ url: '/pages/createStaffQrcode/index' }) },
    ]
  }

  // 处理名称搜索
  const handleNameSearch = (value: string) => {
    setSearchKey(value)
  }

  // 失去焦点时触发搜索
  const handleBlur =() => {
    setFilter(searchKey)
  }

  // 处理状态切换
  const handleStatusChange = () => {
    const newStatus = status === QrcodeStatusEnum.MY ? QrcodeStatusEnum.TEAM : QrcodeStatusEnum.MY
    setStatus(newStatus)
  }

  // 处理新建活码
  const handleCreate = () => {
    setOpen(true)
  }

  return (
    <View className='qrcode-search'>
      <View className='qrcode-search__header'>
        {/* 状态切换 */}
        <View className='qrcode-search__status_nt' onClick={handleStatusChange}>
          {status === QrcodeStatusEnum.MY ? '我的' : '团队'}
          <Exchange size={18} className='search__change_icon' />
        </View>

        {/* 搜索框 */}
        <View className='qrcode-search__input'>
          <IconSearch color='#333' />
          <Input
            className='qrcode-search__field'
            placeholder='请输入活码名称'
            value={searchKey}
            onInput={e => handleNameSearch(e.detail.value)}
            onBlur={handleBlur}
          />
        </View>

        {/* 新建按钮 */}
        <AddOutlined className='qrcode-search__create' size='24' onClick={handleCreate} />
      </View>
      <BtPopup open={open} title={popupCreateMsg.title} onClose={() => setOpen(false)}>
        <View className='qrcode-search__menus'>
          {
            popupCreateMsg.list.map(item => (
              <View className='qrcode-search__menu' key={item.text} onClick={item.onClick}>
                <View className='qrcode-search__menu_title'>{item.text}</View>
                <View className='qrcode-search__menu_tip'>{item.tip}</View>
              </View>
            ))
          }
        </View>
      </BtPopup>
    </View>
  )
}

export default memo(Search)
